package com.dongdong.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.dongdong.data.Result;
import com.dongdong.em.ResultEmnu;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Controller
@RequestMapping("file")
public class FileCotroller {

    @RequestMapping("upLoadFile")
    @ResponseBody
    public Result upload(@RequestParam("myFile")MultipartFile myFile){
         // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String https = "https://";
        String endpoint =  "oss-cn-beijing.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
         String accessKeyId = "LTAI5t6kY5WZdNRifXNnMcev";
         String accessKeySecret = "3yL7KmczqjNP5rh74d602vpTTTNjiy";
        // 填写Bucket名称，例如examplebucket。
         String bucketName = "lebron2105";
        // 填写文件名。文件名包含路径，不包含Bucket名称。例如exampledir/exampleobject.txt。
         String objectName = "image/" + myFile.getOriginalFilename();

         OSS ossClient = null;
         try {
            // 创建OSSClient实例。
            ossClient = new OSSClientBuilder().build(https + endpoint, accessKeyId, accessKeySecret);
            ossClient.putObject(bucketName, objectName, myFile.getInputStream());
        } catch (OSSException e){
            e.printStackTrace();
        } catch (IOException e) {
             e.printStackTrace();
         } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }

         String url = https + bucketName + "." +endpoint + "/" +objectName;
        return Result.respone(ResultEmnu.SUCCESS).setData(url);
    }
}
